package org.mat.ipaas.ucenter.service.modules.api.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.api.dto.DataLog;
import org.mat.ipaas.ucenter.biz.common.api.dto.OnlineAuth;
import org.mat.ipaas.ucenter.biz.common.api.dto.message.*;
import org.mat.ipaas.ucenter.biz.common.system.vo.*;
import org.mat.ipaas.ucenter.biz.common.system.vo.DynamicDataSourceModel;
import org.mat.ipaas.ucenter.biz.common.system.vo.SysFilesModel;
import org.mat.ipaas.ucenter.biz.common.system.vo.SysPermissionDataRuleModel;
import org.mat.ipaas.ucenter.biz.common.system.vo.SysUserCacheInfo;
import org.mat.ipaas.ucenter.biz.common.util.SqlInjectionUtil;
import org.mat.ipaas.ucenter.biz.modules.system.security.DictQueryBlackListHandler;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysUserService;
import org.mat.ipaas.ucenter.biz.modules.system.service.impl.SysBaseApiImpl;
import org.mat.ipaas.ucenter.service.api.open.SystemApiRestAPI;
import org.mat.ipaas.ucenter.service.dto.open.DataLogDTO;
import org.mat.ipaas.ucenter.service.dto.open.OnlineAuthDTO;
import org.mat.ipaas.ucenter.service.dto.open.message.*;
import org.mat.ipaas.ucenter.service.dto.system.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 服务化 system模块 对外接口请求类
 */
@Slf4j
@RestController
@RequestMapping("/sys/api")
public class SystemApiController implements SystemApiRestAPI {

    @Autowired
    private SysBaseApiImpl sysBaseApi;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private DictQueryBlackListHandler dictQueryBlackListHandler;


    /**
     * 发送系统消息
     *
     * @param messageDTO 使用构造器赋值参数 如果不设置category(消息类型)则默认为2 发送系统消息
     */
    @PostMapping("/sendSysAnnouncement")
    public void sendSysAnnouncement(@RequestBody MessageDTO messageDTO) {
        Message message = toMessage(messageDTO);
        sysBaseApi.sendSysAnnouncement(message);
    }


    /**
     * 发送消息 附带业务参数
     *
     * @param messageDTO 使用构造器赋值参数
     */
    @PostMapping("/sendBusAnnouncement")
    public void sendBusAnnouncement(@RequestBody BusMessageDTO messageDTO) {
        BusMessage message = toBusMessage(messageDTO);
        sysBaseApi.sendBusAnnouncement(message);
    }


    /**
     * 通过模板发送消息
     *
     * @param templateMessageDTO 使用构造器赋值参数
     */
    @PostMapping("/sendTemplateAnnouncement")
    public void sendTemplateAnnouncement(@RequestBody TemplateMessageDTO templateMessageDTO) {
        TemplateMessage message = toTemplateMessage(templateMessageDTO);
        sysBaseApi.sendTemplateAnnouncement(message);
    }

    /**
     * 通过模板发送消息 附带业务参数
     *
     * @param busTemplateMessageDTO 使用构造器赋值参数
     */
    @PostMapping("/sendBusTemplateAnnouncement")
    public void sendBusTemplateAnnouncement(@RequestBody BusTemplateMessageDTO busTemplateMessageDTO) {
        BusTemplateMessage busTemplateMessage = toBusTemplateMessage(busTemplateMessageDTO);
        sysBaseApi.sendBusTemplateAnnouncement(busTemplateMessage);
    }

    /**
     * 通过消息中心模板，生成推送内容
     *
     * @param templateDTO 使用构造器赋值参数
     * @return
     */
    @PostMapping("/parseTemplateByCode")
    public String parseTemplateByCode(@RequestBody TemplateDTO templateDTO) {
        Template template = toTemplate(templateDTO);
        return sysBaseApi.parseTemplateByCode(template);
    }

    /**
     * 根据业务类型busType及业务busId修改消息已读
     */
    @GetMapping("/updateSysAnnounReadFlag")
    public void updateSysAnnounReadFlag(@RequestParam("busType") String busType, @RequestParam("busId") String busId) {
        sysBaseApi.updateSysAnnounReadFlag(busType, busId);
    }

    /**
     * 根据用户账号查询用户信息
     *
     * @param username
     * @return
     */
    @GetMapping("/getUserByName")
    public LoginUserDTO getUserByName(@RequestParam("username") String username) {
        LoginUser userByName = sysBaseApi.getUserByName(username);
        log.info("userByName = {}", userByName);
        LoginUserDTO loginUserDTO = toLoginUserDTO(userByName);
        log.info("loginUserDTO = {}", loginUserDTO);
        return loginUserDTO;
    }

    /**
     * 根据用户id查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getUserById")
    public LoginUserDTO getUserById(@RequestParam("id") String id) {
        return toLoginUserDTO(sysBaseApi.getUserById(id));
    }

    /**
     * 通过用户账号查询角色集合
     *
     * @param username
     * @return
     */
    @GetMapping("/getRolesByUsername")
    public List<String> getRolesByUsername(@RequestParam("username") String username) {
        return sysBaseApi.getRolesByUsername(username);
    }

    /**
     * 通过用户账号查询部门集合
     *
     * @param username
     * @return 部门 id
     */
    @GetMapping("/getDepartIdsByUsername")
    public List<String> getDepartIdsByUsername(@RequestParam("username") String username) {
        return sysBaseApi.getDepartIdsByUsername(username);
    }

    /**
     * 通过用户账号查询部门 name
     *
     * @param username
     * @return 部门 name
     */
    @GetMapping("/getDepartNamesByUsername")
    public List<String> getDepartNamesByUsername(@RequestParam("username") String username) {
        return sysBaseApi.getDepartNamesByUsername(username);
    }


    /**
     * 获取数据字典
     *
     * @param code
     * @return
     */
    @GetMapping("/queryDictItemsByCode")
    public List<DictModelDTO> queryDictItemsByCode(@RequestParam("code") String code) {
        return toDictModelDTOList(sysBaseApi.queryDictItemsByCode(code));
    }

    /**
     * 获取有效的数据字典
     *
     * @param code
     * @return
     */
    @GetMapping("/queryEnableDictItemsByCode")
    public List<DictModelDTO> queryEnableDictItemsByCode(@RequestParam("code") String code) {
        return toDictModelDTOList(sysBaseApi.queryEnableDictItemsByCode(code));
    }


    /**
     * 查询所有的父级字典，按照create_time排序
     */
    @GetMapping("/queryAllDict")
    public List<DictModelDTO> queryAllDict() {
        List<DictModel> dictModels = sysBaseApi.queryAllDict();
        return toDictModelDTOList(dictModels);
    }

    /**
     * 查询所有分类字典
     *
     * @return
     */
    @GetMapping("/queryAllSysCategory")
    public List<SysCategoryModelDTO> queryAllSysCategory() {
        List<SysCategoryModel> sysCategoryModels = sysBaseApi.queryAllSysCategory();
        return toSysCategoryModelDTOList(sysCategoryModels);
    }


    /**
     * 查询所有部门 作为字典信息 id -->value,departName -->text
     *
     * @return
     */
    @GetMapping("/queryAllDepartBackDictModel")
    public List<DictModelDTO> queryAllDepartBackDictModel() {
        List<DictModel> dictModels = sysBaseApi.queryAllDepartBackDictModel();
        return toDictModelDTOList(dictModels);
    }

    /**
     * 获取所有角色 带参
     * roleIds 默认选中角色
     *
     * @return
     */
    @GetMapping("/queryAllRole")
    public List<ComboModelDTO> queryAllRole(@RequestParam(name = "roleIds", required = false) String[] roleIds) {
        List<ComboModel> comboModels;
        if (roleIds == null || roleIds.length == 0) {
            comboModels = sysBaseApi.queryAllRole();
        } else {
            comboModels = sysBaseApi.queryAllRole(roleIds);
        }

        return toComboModelDTOList(comboModels);
    }

    /**
     * 通过用户账号查询角色Id集合
     *
     * @param username
     * @return
     */
    @GetMapping("/getRoleIdsByUsername")
    public List<String> getRoleIdsByUsername(@RequestParam("username") String username) {
        return sysBaseApi.getRoleIdsByUsername(username);
    }

    /**
     * 通过部门编号查询部门id
     *
     * @param orgCode
     * @return
     */
    @GetMapping("/getDepartIdsByOrgCode")
    public String getDepartIdsByOrgCode(@RequestParam("orgCode") String orgCode) {
        return sysBaseApi.getDepartIdsByOrgCode(orgCode);
    }

    /**
     * 查询所有部门
     *
     * @return
     */
    @GetMapping("/getAllSysDepart")
    public List<SysDepartModelDTO> getAllSysDepart() {
        List<SysDepartModel> allSysDepart = sysBaseApi.getAllSysDepart();
        return toSysDepartModelDTOList(allSysDepart);
    }

    /**
     * 根据 id 查询数据库中存储的 DynamicDataSourceModel
     *
     * @param dbSourceId
     * @return
     */
    @GetMapping("/getDynamicDbSourceById")
    public DynamicDataSourceModelDTO getDynamicDbSourceById(@RequestParam("dbSourceId") String dbSourceId) {
        DynamicDataSourceModel dynamicDbSourceById = sysBaseApi.getDynamicDbSourceById(dbSourceId);
        return toDynamicDataSourceModelDTO(dynamicDbSourceById);
    }


    /**
     * 根据部门Id获取部门负责人
     *
     * @param deptId
     * @return
     */
    @GetMapping("/getDeptHeadByDepId")
    public List<String> getDeptHeadByDepId(@RequestParam("deptId") String deptId) {
        return sysBaseApi.getDeptHeadByDepId(deptId);
    }

    /**
     * 查找父级部门
     *
     * @param departId
     * @return
     */
    @GetMapping("/getParentDepartId")
    public DictModelDTO getParentDepartId(@RequestParam("departId") String departId) {
        DictModel parentDepartId = sysBaseApi.getParentDepartId(departId);
        return toDictModelDTO(parentDepartId);
    }

    /**
     * 根据 code 查询数据库中存储的 DynamicDataSourceModel
     *
     * @param dbSourceCode
     * @return
     */
    @GetMapping("/getDynamicDbSourceByCode")
    public DynamicDataSourceModelDTO getDynamicDbSourceByCode(@RequestParam("dbSourceCode") String dbSourceCode) {
        DynamicDataSourceModel dynamicDbSourceByCode = sysBaseApi.getDynamicDbSourceByCode(dbSourceCode);
        return toDynamicDataSourceModelDTO(dynamicDbSourceByCode);
    }

    /**
     * 给指定用户发消息
     *
     * @param userIds
     * @param cmd
     */
    @GetMapping("/sendWebSocketMsg")
    public void sendWebSocketMsg(String[] userIds, String cmd) {
        sysBaseApi.sendWebSocketMsg(userIds, cmd);
    }


    /**
     * 根据id获取所有参与用户
     * userIds
     *
     * @return
     */
    @GetMapping("/queryAllUserByIds")
    public List<LoginUserDTO> queryAllUserByIds(@RequestParam("userIds") String[] userIds) {
        List<LoginUser> loginUsers = sysBaseApi.queryAllUserByIds(userIds);
        return toLoginUserDTOList(loginUsers);
    }

    /**
     * 查询所有用户 返回ComboModel
     *
     * @return
     */
    @GetMapping("/queryAllUserBackCombo")
    public List<ComboModelDTO> queryAllUserBackCombo() {
        List<ComboModel> comboModels = sysBaseApi.queryAllUserBackCombo();
        return toComboModelDTOList(comboModels);
    }

    /**
     * 分页查询用户 返回JSONObject
     *
     * @return
     */
    @GetMapping("/queryAllUser")
    public JSONObject queryAllUser(@RequestParam(name = "userIds", required = false) String userIds, @RequestParam(name = "pageNo", required = false) Integer pageNo, @RequestParam(name = "pageSize", required = false) int pageSize) {
        return sysBaseApi.queryAllUser(userIds, pageNo, pageSize);
    }


    /**
     * 将会议签到信息推动到预览
     * userIds
     *
     * @param userId
     * @return
     */
    @GetMapping("/meetingSignWebsocket")
    public void meetingSignWebsocket(@RequestParam("userId") String userId) {
        sysBaseApi.meetingSignWebsocket(userId);
    }

    /**
     * 根据name获取所有参与用户
     * userNames
     *
     * @return
     */
    @GetMapping("/queryUserByNames")
    public List<LoginUserDTO> queryUserByNames(@RequestParam("userNames") String[] userNames) {
        List<LoginUser> loginUsers = sysBaseApi.queryUserByNames(userNames);
        return toLoginUserDTOList(loginUsers);
    }

    /**
     * 获取用户的角色集合
     *
     * @param username
     * @return
     */
    @GetMapping("/getUserRoleSet")
    public Set<String> getUserRoleSet(@RequestParam("username") String username) {
        return sysBaseApi.getUserRoleSet(username);
    }

    /**
     * 获取用户的权限集合
     *
     * @param username
     * @return
     */
    @GetMapping("/getUserPermissionSet")
    public Set<String> getUserPermissionSet(@RequestParam("username") String username) {
        return sysBaseApi.getUserPermissionSet(username);
    }

    //-----

    /**
     * 判断是否有online访问的权限
     *
     * @param onlineAuthDTO
     * @return
     */
    @PostMapping("/hasOnlineAuth")
    public boolean hasOnlineAuth(@RequestBody OnlineAuthDTO onlineAuthDTO) {
        OnlineAuth onlineAuth = toOnlineAuth(onlineAuthDTO);

        return sysBaseApi.hasOnlineAuth(onlineAuth);
    }

    /**
     * 查询用户角色信息
     *
     * @param username
     * @return
     */
    @GetMapping("/queryUserRoles")
    public Set<String> queryUserRoles(@RequestParam("username") String username) {
        return sysUserService.getUserRolesSet(username);
    }


    /**
     * 查询用户权限信息
     *
     * @param username
     * @return
     */
    @GetMapping("/queryUserAuths")
    public Set<String> queryUserAuths(@RequestParam("username") String username) {
        return sysUserService.getUserPermissionsSet(username);
    }

    /**
     * 通过部门id获取部门全部信息
     */
    @GetMapping("/selectAllById")
    public SysDepartModelDTO selectAllById(@RequestParam("id") String id) {
        SysDepartModel sysDepartModel = sysBaseApi.selectAllById(id);
        return toSysDepartModelDTO(sysDepartModel);
    }

    /**
     * 根据用户id查询用户所属公司下所有用户ids
     *
     * @param userId
     * @return
     */
    @GetMapping("/queryDeptUsersByUserId")
    public List<String> queryDeptUsersByUserId(@RequestParam("userId") String userId) {
        return sysBaseApi.queryDeptUsersByUserId(userId);
    }


    /**
     * 查询数据权限
     *
     * @return
     */
    @GetMapping("/queryPermissionDataRule")
    public List<SysPermissionDataRuleModelDTO> queryPermissionDataRule(@RequestParam("component") String component, @RequestParam("requestPath") String requestPath, @RequestParam("username") String username) {
        List<SysPermissionDataRuleModel> sysPermissionDataRuleModels = sysBaseApi.queryPermissionDataRule(component, requestPath, username);
        return toSysPermissionDataRuleModelDTOList(sysPermissionDataRuleModels);
    }

    /**
     * 查询用户信息
     *
     * @param username
     * @return
     */
    @GetMapping("/getCacheUser")
    public SysUserCacheInfoDTO getCacheUser(@RequestParam("username") String username) {
        SysUserCacheInfo cacheUser = sysBaseApi.getCacheUser(username);
        return toSysUserCacheInfoDTO(cacheUser);
    }

    /**
     * 普通字典的翻译
     *
     * @param code
     * @param key
     * @return
     */
    @GetMapping("/translateDict")
    public String translateDict(@RequestParam("code") String code, @RequestParam("key") String key) {
        return sysBaseApi.translateDict(code, key);
    }


    /**
     * 36根据多个用户账号(逗号分隔)，查询返回多个用户信息
     *
     * @param usernames
     * @return
     */
    @RequestMapping("/queryUsersByUsernames")
    public List<JSONObject> queryUsersByUsernames(@RequestParam("usernames") String usernames) {
        return this.sysBaseApi.queryUsersByUsernames(usernames);
    }

    /**
     * 37根据多个用户id(逗号分隔)，查询返回多个用户信息
     *
     * @param ids
     * @return
     */
    @RequestMapping("/queryUsersByIds")
    public List<JSONObject> queryUsersByIds(@RequestParam("ids") String ids) {
        return this.sysBaseApi.queryUsersByIds(ids);
    }

    /**
     * 38根据多个部门编码(逗号分隔)，查询返回多个部门信息
     *
     * @param orgCodes
     * @return
     */
    @GetMapping("/queryDepartsByOrgcodes")
    public List<JSONObject> queryDepartsByOrgcodes(@RequestParam("orgCodes") String orgCodes) {
        return this.sysBaseApi.queryDepartsByOrgcodes(orgCodes);
    }

    /**
     * 39根据多个部门ID(逗号分隔)，查询返回多个部门信息
     *
     * @param ids
     * @return
     */
    @GetMapping("/queryDepartsByIds")
    public List<JSONObject> queryDepartsByIds(@RequestParam("ids") String ids) {
        return this.sysBaseApi.queryDepartsByIds(ids);
    }

    /**
     * 40发送邮件消息
     *
     * @param email
     * @param title
     * @param content
     */
    @GetMapping("/sendEmailMsg")
    public void sendEmailMsg(@RequestParam("email") String email, @RequestParam("title") String title, @RequestParam("content") String content) {
        this.sysBaseApi.sendEmailMsg(email, title, content);
    }

    ;

    /**
     * 41 获取公司下级部门和公司下所有用户信息
     *
     * @param orgCode
     */
    @GetMapping("/getDeptUserByOrgCode")
    public List<Map> getDeptUserByOrgCode(@RequestParam("orgCode") String orgCode) {
        return this.sysBaseApi.getDeptUserByOrgCode(orgCode);
    }

    /**
     * 查询分类字典翻译
     *
     * @param ids 分类字典表id
     * @return
     */
    @GetMapping("/loadCategoryDictItem")
    public List<String> loadCategoryDictItem(@RequestParam("ids") String ids) {
        return sysBaseApi.loadCategoryDictItem(ids);
    }

    /**
     * 根据字典code加载字典text
     *
     * @param dictCode 顺序：tableName,text,code
     * @param keys     要查询的key
     * @return
     */
    @GetMapping("/loadDictItem")
    public List<String> loadDictItem(@RequestParam("dictCode") String dictCode, @RequestParam("keys") String keys) {
        if (!dictQueryBlackListHandler.isPass(dictCode)) {
            log.error(dictQueryBlackListHandler.getError());
            return null;
        }
        return sysBaseApi.loadDictItem(dictCode, keys);
    }

    /**
     * 根据字典code查询字典项
     *
     * @param dictCode 顺序：tableName,text,code
     * @param dictCode 要查询的key
     * @return
     */
    @GetMapping("/getDictItems")
    public List<DictModelDTO> getDictItems(@RequestParam("dictCode") String dictCode) {
        if (!dictQueryBlackListHandler.isPass(dictCode)) {
            log.error(dictQueryBlackListHandler.getError());
            return null;
        }
        List<DictModel> dictItems = sysBaseApi.getDictItems(dictCode);
        return toDictModelDTOList(dictItems);
    }

    /**
     * 根据多个字典code查询多个字典项
     *
     * @param dictCodeList
     * @return key = dictCode ； value=对应的字典项
     */
    @RequestMapping("/getManyDictItems")
    public Map<String, ?> getManyDictItems(@RequestParam("dictCodeList") List<String> dictCodeList) {
        Map<String, List<DictModel>> manyDictItems = sysBaseApi.getManyDictItems(dictCodeList);
        return manyDictItems;
    }

    /**
     * 【下拉搜索】
     * 大数据量的字典表 走异步加载，即前端输入内容过滤数据
     *
     * @param dictCode 字典code格式：table,text,code
     * @param keyword  过滤关键字
     * @return
     */
    @GetMapping("/loadDictItemByKeyword")
    public List<DictModelDTO> loadDictItemByKeyword(@RequestParam("dictCode") String dictCode, @RequestParam("keyword") String keyword, @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        if (!dictQueryBlackListHandler.isPass(dictCode)) {
            log.error(dictQueryBlackListHandler.getError());
            return null;
        }
        List<DictModel> dictModels = sysBaseApi.loadDictItemByKeyword(dictCode, keyword, pageSize);
        return toDictModelDTOList(dictModels);
    }

    /**
     * 48 普通字典的翻译，根据多个dictCode和多条数据，多个以逗号分割
     *
     * @param dictCodes
     * @param keys
     * @return
     */
    @GetMapping("/translateManyDict")
    public Map<String, ?> translateManyDict(@RequestParam("dictCodes") String dictCodes, @RequestParam("keys") String keys) {
        return this.sysBaseApi.translateManyDict(dictCodes, keys);
    }


    /**
     * 获取表数据字典 【接口签名验证】
     *
     * @param table
     * @param text
     * @param code
     * @return
     */
    @GetMapping("/queryTableDictItemsByCode")
    public List<DictModelDTO> queryTableDictItemsByCode(@RequestParam("table") String table, @RequestParam("text") String text, @RequestParam("code") String code) {
        String str = table + "," + text + "," + code;
        if (!dictQueryBlackListHandler.isPass(str)) {
            log.error(dictQueryBlackListHandler.getError());
            return null;
        }
        List<DictModel> dictModels = sysBaseApi.queryTableDictItemsByCode(table, text, code);
        return toDictModelDTOList(dictModels);
    }

    /**
     * 查询表字典 支持过滤数据 【接口签名验证】
     *
     * @param table
     * @param text
     * @param code
     * @param filterSql
     * @return
     */
    @GetMapping("/queryFilterTableDictInfo")
    public List<DictModelDTO> queryFilterTableDictInfo(@RequestParam("table") String table, @RequestParam("text") String text, @RequestParam("code") String code, @RequestParam("filterSql") String filterSql) {
        String str = table + "," + text + "," + code;
        if (!dictQueryBlackListHandler.isPass(str)) {
            log.error(dictQueryBlackListHandler.getError());
            return null;
        }
        String[] arr = new String[]{table, text, code};
        SqlInjectionUtil.filterContent(arr);
        SqlInjectionUtil.specialFilterContentForDictSql(filterSql);
        List<DictModel> dictModels = sysBaseApi.queryFilterTableDictInfo(table, text, code, filterSql);
        return toDictModelDTOList(dictModels);
    }

    /**
     * 【接口签名验证】
     * 查询指定table的 text code 获取字典，包含text和value
     *
     * @param table
     * @param text
     * @param code
     * @param keyArray
     * @return
     */
    @Deprecated
    @GetMapping("/queryTableDictByKeys")
    public List<String> queryTableDictByKeys(@RequestParam("table") String table, @RequestParam("text") String text, @RequestParam("code") String code, @RequestParam("keyArray") String[] keyArray) {
        String str = table + "," + text + "," + code;
        if (!dictQueryBlackListHandler.isPass(str)) {
            log.error(dictQueryBlackListHandler.getError());
            return null;
        }
        return sysBaseApi.queryTableDictByKeys(table, text, code, keyArray);
    }


    /**
     * 字典表的 翻译【接口签名验证】
     *
     * @param table
     * @param text
     * @param code
     * @param key
     * @return
     */
    @GetMapping("/translateDictFromTable")
    public String translateDictFromTable(@RequestParam("table") String table, @RequestParam("text") String text, @RequestParam("code") String code, @RequestParam("key") String key) {
        String str = table + "," + text + "," + code;
        if (!dictQueryBlackListHandler.isPass(str)) {
            log.error(dictQueryBlackListHandler.getError());
            return null;
        }
        String[] arr = new String[]{table, text, code, key};
        SqlInjectionUtil.filterContent(arr);
        return sysBaseApi.translateDictFromTable(table, text, code, key);
    }


    /**
     * 【接口签名验证】
     * 49 字典表的 翻译，可批量
     *
     * @param table
     * @param text
     * @param code
     * @param keys  多个用逗号分割
     * @return
     */
    @GetMapping("/translateDictFromTableByKeys")
    public List<DictModelDTO> translateDictFromTableByKeys(@RequestParam("table") String table, @RequestParam("text") String text, @RequestParam("code") String code, @RequestParam("keys") String keys) {
        String str = table + "," + text + "," + code;
        if (!dictQueryBlackListHandler.isPass(str)) {
            log.error(dictQueryBlackListHandler.getError());
            return null;
        }
        List<DictModel> dictModels = this.sysBaseApi.translateDictFromTableByKeys(table, text, code, keys);
        return toDictModelDTOList(dictModels);
    }

    /**
     * 发送模板信息
     *
     * @param messageDTO
     */
    @PostMapping("/sendTemplateMessage")
    public void sendTemplateMessage(@RequestBody MessageDTO messageDTO) {
        Message message = toMessage(messageDTO);

        sysBaseApi.sendTemplateMessage(message);
    }

    /**
     * 获取消息模板内容
     *
     * @param code
     * @return
     */
    @GetMapping("/getTemplateContent")
    public String getTemplateContent(@RequestParam("code") String code) {
        return this.sysBaseApi.getTemplateContent(code);
    }

    /**
     * 保存数据日志
     *
     * @param dataLogDTO
     */
    @PostMapping("/saveDataLog")
    public void saveDataLog(@RequestBody DataLogDTO dataLogDTO) {
        DataLog dataLog = toDataLog(dataLogDTO);
        this.sysBaseApi.saveDataLog(dataLog);
    }

    @PostMapping("/addSysFiles")
    public void addSysFiles(@RequestBody SysFilesModelDTO sysFilesModelDTO) {
        SysFilesModel sysFilesModel = toSysFilesModel(sysFilesModelDTO);
        this.sysBaseApi.addSysFiles(sysFilesModel);
    }

    @GetMapping("/getFileUrl")
    public String getFileUrl(@RequestParam(name = "fileId") String fileId) {
        return this.sysBaseApi.getFileUrl(fileId);
    }

    /**
     * 更新头像
     *
     * @param loginUserDTO
     * @return
     */
    @PutMapping("/updateAvatar")
    public void updateAvatar(@RequestBody LoginUserDTO loginUserDTO) {
        LoginUser loginUser = toLoginUser(loginUserDTO);
        this.sysBaseApi.updateAvatar(loginUser);
    }

    /**
     * 向app端 websocket推送聊天刷新消息
     *
     * @param userId
     * @return
     */
    @GetMapping("/sendAppChatSocket")
    public void sendAppChatSocket(@RequestParam(name = "userId") String userId) {
        this.sysBaseApi.sendAppChatSocket(userId);
    }


    /**
     * VUEN-2584【issue】平台sql注入漏洞几个问题
     * 部分特殊函数 可以将查询结果混夹在错误信息中，导致数据库的信息暴露
     *
     * @param e
     * @return
     */
    @ExceptionHandler(java.sql.SQLException.class)
    public MatApiResponse<?> handleSQLException(Exception e) {
        String msg = e.getMessage();
        String extractvalue = "extractvalue";
        String updatexml = "updatexml";
        if (msg != null && (msg.toLowerCase().indexOf(extractvalue) >= 0 || msg.toLowerCase().indexOf(updatexml) >= 0)) {
            return MatApiResponse.fail("校验失败，sql解析异常！");
        }
        return MatApiResponse.fail("校验失败，sql解析异常！" + msg);
    }


    private Message toMessage(MessageDTO messageDTO) {
        if (messageDTO == null) {
            return null;
        }
        Message message = new Message();
        message.setFromUser(messageDTO.getFromUser());
        message.setToUser(messageDTO.getToUser());
        message.setToAll(messageDTO.getToAll());
        message.setTitle(messageDTO.getTitle());
        message.setContent(messageDTO.getContent());
        message.setCategory(messageDTO.getCategory());
        message.setTemplateCode(messageDTO.getTemplateCode());
        message.setType(messageDTO.getType());
        message.setIsMarkdown(messageDTO.isMarkdown());
        message.setData(messageDTO.getData());
        message.setCopyToUser(messageDTO.getCopyToUser());
        return message;
    }


    private BusMessage toBusMessage(BusMessageDTO messageDTO) {
        if (messageDTO == null) {
            return null;
        }
        BusMessage busMessage = new BusMessage();
        busMessage.setBusType(messageDTO.getBusType());
        busMessage.setBusId(messageDTO.getBusId());
        busMessage.setFromUser(messageDTO.getFromUser());
        busMessage.setToUser(messageDTO.getToUser());
        busMessage.setToAll(messageDTO.getToAll());
        busMessage.setTitle(messageDTO.getTitle());
        busMessage.setContent(messageDTO.getContent());
        busMessage.setCategory(messageDTO.getCategory());
        busMessage.setTemplateCode(messageDTO.getTemplateCode());
        busMessage.setType(messageDTO.getType());
        busMessage.setIsMarkdown(messageDTO.isMarkdown());
        busMessage.setData(messageDTO.getData());
        busMessage.setCopyToUser(messageDTO.getCopyToUser());
        return busMessage;
    }


    private TemplateMessage toTemplateMessage(TemplateMessageDTO templateMessageDTO) {
        if (templateMessageDTO == null) {
            return null;
        }
        TemplateMessage templateMessage = new TemplateMessage();
        templateMessage.setFromUser(templateMessageDTO.getFromUser());
        templateMessage.setToUser(templateMessageDTO.getToUser());
        templateMessage.setTitle(templateMessageDTO.getTitle());
        templateMessage.setTemplateCode(templateMessageDTO.getTemplateCode());
        templateMessage.setTemplateParam(templateMessageDTO.getTemplateParam());
        return templateMessage;
    }


    private BusTemplateMessage toBusTemplateMessage(BusTemplateMessageDTO busTemplateMessageDTO) {
        if (busTemplateMessageDTO == null) {
            return null;
        }
        BusTemplateMessage busTemplateMessage = new BusTemplateMessage();
        busTemplateMessage.setBusType(busTemplateMessageDTO.getBusType());
        busTemplateMessage.setBusId(busTemplateMessageDTO.getBusId());
        busTemplateMessage.setFromUser(busTemplateMessageDTO.getFromUser());
        busTemplateMessage.setToUser(busTemplateMessageDTO.getToUser());
        busTemplateMessage.setTitle(busTemplateMessageDTO.getTitle());
        busTemplateMessage.setTemplateCode(busTemplateMessageDTO.getTemplateCode());
        busTemplateMessage.setTemplateParam(busTemplateMessageDTO.getTemplateParam());
        return busTemplateMessage;
    }


    private Template toTemplate(TemplateDTO templateDTO) {
        if (templateDTO == null) {
            return null;
        }
        Template template = new Template();
        template.setTemplateCode(templateDTO.getTemplateCode());
        template.setTemplateParam(templateDTO.getTemplateParam());
        return template;
    }


    private LoginUserDTO toLoginUserDTO(LoginUser loginUser) {
        if (loginUser == null) {
            return null;
        }
        LoginUserDTO loginUserDTO = new LoginUserDTO();
        loginUserDTO.setId(loginUser.getId());
        loginUserDTO.setUsername(loginUser.getUsername());
        loginUserDTO.setRealname(loginUser.getRealname());
        loginUserDTO.setPassword(loginUser.getPassword());
        loginUserDTO.setOrgCode(loginUser.getOrgCode());
        loginUserDTO.setAvatar(loginUser.getAvatar());
        loginUserDTO.setBirthday(loginUser.getBirthday());
        loginUserDTO.setSex(loginUser.getSex());
        loginUserDTO.setEmail(loginUser.getEmail());
        loginUserDTO.setPhone(loginUser.getPhone());
        loginUserDTO.setStatus(loginUser.getStatus());
        loginUserDTO.setDelFlag(loginUser.getDelFlag());
        loginUserDTO.setActivitiSync(loginUser.getActivitiSync());
        loginUserDTO.setCreateTime(loginUser.getCreateTime());
        loginUserDTO.setUserIdentity(loginUser.getUserIdentity());
        loginUserDTO.setDepartIds(loginUser.getDepartIds());
        loginUserDTO.setPost(loginUser.getPost());
        loginUserDTO.setTelephone(loginUser.getTelephone());
        loginUserDTO.setRelTenantIds(loginUser.getRelTenantIds());
        loginUserDTO.setClientId(loginUser.getClientId());
        return loginUserDTO;
    }

    private List<DictModelDTO> toDictModelDTOList(List<DictModel> ls) {
        List<DictModelDTO> dictModelDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ls)) {
            for (DictModel dictModel : ls) {
                dictModelDTOList.add(toDictModelDTO(dictModel));
            }
        }
        return dictModelDTOList;
    }

    private DictModelDTO toDictModelDTO(DictModel dictModel) {
        if (dictModel == null) {
            return null;
        }
        DictModelDTO dictModelDTO = new DictModelDTO();
        dictModelDTO.setValue(dictModel.getValue());
        dictModelDTO.setText(dictModel.getText());
        return dictModelDTO;
    }


    private List<SysCategoryModelDTO> toSysCategoryModelDTOList(List<SysCategoryModel> sysCategoryModels) {
        List<SysCategoryModelDTO> sysCategoryModelDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(sysCategoryModels)) {
            for (SysCategoryModel sysCategoryModel : sysCategoryModels) {
                sysCategoryModelDTOList.add(toSysCategoryModelDTO(sysCategoryModel));
            }
        }
        return sysCategoryModelDTOList;
    }

    private SysCategoryModelDTO toSysCategoryModelDTO(SysCategoryModel sysCategoryModel) {
        if (sysCategoryModel == null) {
            return null;
        }
        SysCategoryModelDTO sysCategoryModelDTO = new SysCategoryModelDTO();
        sysCategoryModelDTO.setId(sysCategoryModel.getId());
        sysCategoryModelDTO.setPid(sysCategoryModel.getPid());
        sysCategoryModelDTO.setName(sysCategoryModel.getName());
        sysCategoryModelDTO.setCode(sysCategoryModel.getCode());
        return sysCategoryModelDTO;
    }


    private List<ComboModelDTO> toComboModelDTOList(List<ComboModel> comboModels) {
        List<ComboModelDTO> comboModelDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(comboModels)) {
            for (ComboModel comboModel : comboModels) {
                comboModelDTOList.add(toComboModelDTO(comboModel));
            }
        }

        return comboModelDTOList;
    }

    private ComboModelDTO toComboModelDTO(ComboModel comboModel) {
        if (comboModel == null) {
            return null;
        }
        ComboModelDTO comboModelDTO = new ComboModelDTO();
        comboModelDTO.setId(comboModel.getId());
        comboModelDTO.setTitle(comboModel.getTitle());
        comboModelDTO.setChecked(comboModel.isChecked());
        comboModelDTO.setUsername(comboModel.getUsername());
        comboModelDTO.setEmail(comboModel.getEmail());
        comboModelDTO.setRoleCode(comboModel.getRoleCode());
        return comboModelDTO;
    }


    private List<SysDepartModelDTO> toSysDepartModelDTOList(List<SysDepartModel> allSysDepart) {
        List<SysDepartModelDTO> sysDepartModelDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(allSysDepart)) {
            for (SysDepartModel sysDepartModel : allSysDepart) {
                sysDepartModelDTOList.add(toSysDepartModelDTO(sysDepartModel));
            }
        }

        return sysDepartModelDTOList;
    }

    private SysDepartModelDTO toSysDepartModelDTO(SysDepartModel sysDepartModel) {
        if (sysDepartModel == null) {
            return null;
        }
        SysDepartModelDTO sysDepartModelDTO = new SysDepartModelDTO();
        sysDepartModelDTO.setId(sysDepartModel.getId());
        sysDepartModelDTO.setParentId(sysDepartModel.getParentId());
        sysDepartModelDTO.setDepartName(sysDepartModel.getDepartName());
        sysDepartModelDTO.setDepartNameEn(sysDepartModel.getDepartNameEn());
        sysDepartModelDTO.setDepartNameAbbr(sysDepartModel.getDepartNameAbbr());
        sysDepartModelDTO.setDepartOrder(sysDepartModel.getDepartOrder());
        sysDepartModelDTO.setDescription(sysDepartModel.getDescription());
        sysDepartModelDTO.setOrgCategory(sysDepartModel.getOrgCategory());
        sysDepartModelDTO.setOrgType(sysDepartModel.getOrgType());
        sysDepartModelDTO.setOrgCode(sysDepartModel.getOrgCode());
        sysDepartModelDTO.setMobile(sysDepartModel.getMobile());
        sysDepartModelDTO.setFax(sysDepartModel.getFax());
        sysDepartModelDTO.setAddress(sysDepartModel.getAddress());
        sysDepartModelDTO.setMemo(sysDepartModel.getMemo());
        return sysDepartModelDTO;
    }


    private DynamicDataSourceModelDTO toDynamicDataSourceModelDTO(DynamicDataSourceModel dynamicDbSourceById) {
        if (dynamicDbSourceById == null) {
            return null;
        }
        DynamicDataSourceModelDTO dynamicDataSourceModelDTO = new DynamicDataSourceModelDTO();
        dynamicDataSourceModelDTO.setId(dynamicDbSourceById.getId());
        dynamicDataSourceModelDTO.setCode(dynamicDbSourceById.getCode());
        dynamicDataSourceModelDTO.setDbType(dynamicDbSourceById.getDbType());
        dynamicDataSourceModelDTO.setDbDriver(dynamicDbSourceById.getDbDriver());
        dynamicDataSourceModelDTO.setDbUrl(dynamicDbSourceById.getDbUrl());
        dynamicDataSourceModelDTO.setDbUsername(dynamicDbSourceById.getDbUsername());
        dynamicDataSourceModelDTO.setDbPassword(dynamicDbSourceById.getDbPassword());
        return dynamicDataSourceModelDTO;
    }


    private List<LoginUserDTO> toLoginUserDTOList(List<LoginUser> loginUsers) {
        List<LoginUserDTO> loginUserDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(loginUsers)) {
            for (LoginUser loginUser : loginUsers) {
                loginUserDTOList.add(toLoginUserDTO(loginUser));
            }
        }

        return loginUserDTOList;
    }


    private OnlineAuth toOnlineAuth(OnlineAuthDTO onlineAuthDTO) {
        if (onlineAuthDTO == null) {
            return null;
        }
        OnlineAuth onlineAuth = new OnlineAuth();
        onlineAuth.setUsername(onlineAuthDTO.getUsername());
        onlineAuth.setPossibleUrl(onlineAuthDTO.getPossibleUrl());
        onlineAuth.setOnlineFormUrl(onlineAuthDTO.getOnlineFormUrl());
        return onlineAuth;
    }


    private List<SysPermissionDataRuleModelDTO> toSysPermissionDataRuleModelDTOList(List<SysPermissionDataRuleModel> sysPermissionDataRuleModels) {
        List<SysPermissionDataRuleModelDTO> sysPermissionDataRuleModelDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(sysPermissionDataRuleModels)) {
            for (SysPermissionDataRuleModel sysPermissionDataRuleModel : sysPermissionDataRuleModels) {
                sysPermissionDataRuleModelDTOList.add(toSysPermissionDataRuleModelDTO(sysPermissionDataRuleModel));
            }
        }

        return sysPermissionDataRuleModelDTOList;
    }

    private SysPermissionDataRuleModelDTO toSysPermissionDataRuleModelDTO(SysPermissionDataRuleModel sysPermissionDataRuleModel) {
        if (sysPermissionDataRuleModel == null) {
            return null;
        }
        SysPermissionDataRuleModelDTO sysPermissionDataRuleModelDTO = new SysPermissionDataRuleModelDTO();
        sysPermissionDataRuleModelDTO.setId(sysPermissionDataRuleModel.getId());
        sysPermissionDataRuleModelDTO.setPermissionId(sysPermissionDataRuleModel.getPermissionId());
        sysPermissionDataRuleModelDTO.setRuleName(sysPermissionDataRuleModel.getRuleName());
        sysPermissionDataRuleModelDTO.setRuleColumn(sysPermissionDataRuleModel.getRuleColumn());
        sysPermissionDataRuleModelDTO.setRuleConditions(sysPermissionDataRuleModel.getRuleConditions());
        sysPermissionDataRuleModelDTO.setRuleValue(sysPermissionDataRuleModel.getRuleValue());
        sysPermissionDataRuleModelDTO.setCreateTime(sysPermissionDataRuleModel.getCreateTime());
        sysPermissionDataRuleModelDTO.setCreateBy(sysPermissionDataRuleModel.getCreateBy());
        sysPermissionDataRuleModelDTO.setUpdateTime(sysPermissionDataRuleModel.getUpdateTime());
        sysPermissionDataRuleModelDTO.setUpdateBy(sysPermissionDataRuleModel.getUpdateBy());
        return sysPermissionDataRuleModelDTO;
    }


    private SysUserCacheInfoDTO toSysUserCacheInfoDTO(SysUserCacheInfo cacheUser) {
        if (cacheUser == null) {
            return null;
        }
        SysUserCacheInfoDTO sysUserCacheInfoDTO = new SysUserCacheInfoDTO();
        sysUserCacheInfoDTO.setSysUserCode(cacheUser.getSysUserCode());
        sysUserCacheInfoDTO.setSysUserName(cacheUser.getSysUserName());
        sysUserCacheInfoDTO.setSysOrgCode(cacheUser.getSysOrgCode());
        sysUserCacheInfoDTO.setSysMultiOrgCode(cacheUser.getSysMultiOrgCode());
        sysUserCacheInfoDTO.setOneDepart(cacheUser.isOneDepart());
        return sysUserCacheInfoDTO;
    }


    private DataLog toDataLog(DataLogDTO dataLogDTO) {
        if (dataLogDTO == null) {
            return null;
        }
        DataLog dataLog = new DataLog();
        dataLog.setTableName(dataLogDTO.getTableName());
        dataLog.setDataId(dataLogDTO.getDataId());
        dataLog.setContent(dataLogDTO.getContent());
        dataLog.setType(dataLogDTO.getType());
        return dataLog;
    }


    private SysFilesModel toSysFilesModel(SysFilesModelDTO sysFilesModelDTO) {
        if (sysFilesModelDTO == null) {
            return null;
        }
        SysFilesModel sysFilesModel = new SysFilesModel();
        sysFilesModel.setId(sysFilesModelDTO.getId());
        sysFilesModel.setFileName(sysFilesModelDTO.getFileName());
        sysFilesModel.setUrl(sysFilesModelDTO.getUrl());
        sysFilesModel.setFileType(sysFilesModelDTO.getFileType());
        sysFilesModel.setStoreType(sysFilesModelDTO.getStoreType());
        sysFilesModel.setFileSize(sysFilesModelDTO.getFileSize());
        return sysFilesModel;
    }


    private LoginUser toLoginUser(LoginUserDTO loginUserDTO) {
        if (loginUserDTO == null) {
            return null;
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setId(loginUserDTO.getId());
        loginUser.setUsername(loginUserDTO.getUsername());
        loginUser.setRealname(loginUserDTO.getRealname());
        loginUser.setPassword(loginUserDTO.getPassword());
        loginUser.setOrgCode(loginUserDTO.getOrgCode());
        loginUser.setAvatar(loginUserDTO.getAvatar());
        loginUser.setBirthday(loginUserDTO.getBirthday());
        loginUser.setSex(loginUserDTO.getSex());
        loginUser.setEmail(loginUserDTO.getEmail());
        loginUser.setPhone(loginUserDTO.getPhone());
        loginUser.setStatus(loginUserDTO.getStatus());
        loginUser.setDelFlag(loginUserDTO.getDelFlag());
        loginUser.setActivitiSync(loginUserDTO.getActivitiSync());
        loginUser.setCreateTime(loginUserDTO.getCreateTime());
        loginUser.setUserIdentity(loginUserDTO.getUserIdentity());
        loginUser.setDepartIds(loginUserDTO.getDepartIds());
        loginUser.setPost(loginUserDTO.getPost());
        loginUser.setTelephone(loginUserDTO.getTelephone());
        loginUser.setRelTenantIds(loginUserDTO.getRelTenantIds());
        loginUser.setClientId(loginUserDTO.getClientId());
        return loginUser;
    }

}
